import { IpcRenderer } from 'electron'

/**
 * Photos API 封装类
 * 提供类型安全的 IPC 通信接口
 */
export class PhotosAPI {
  private ipcRenderer: IpcRenderer
  private listeners: Map<string, Function[]> = new Map()

  constructor(ipcRenderer: IpcRenderer) {
    this.ipcRenderer = ipcRenderer
  }

  // 应用信息相关
  async getAppVersion(): Promise<string> {
    return this.ipcRenderer.invoke('app:get-version')
  }

  async getAppName(): Promise<string> {
    return this.ipcRenderer.invoke('app:get-name')
  }

  async getAppPath(name: string): Promise<string> {
    return this.ipcRenderer.invoke('app:get-path', name)
  }

  // 对话框相关
  async openDirectoryDialog(): Promise<{ canceled: boolean; filePaths: string[] }> {
    return this.ipcRenderer.invoke('dialog:open-directory')
  }

  async showMessageDialog(options: any): Promise<any> {
    return this.ipcRenderer.invoke('dialog:show-message', options)
  }

  async showErrorDialog(title: string, content: string): Promise<void> {
    return this.ipcRenderer.invoke('dialog:show-error', title, content)
  }

  // 文件系统相关
  async scanDirectory(path: string): Promise<any[]> {
    return this.ipcRenderer.invoke('fs:scan-directory', path)
  }

  // 数据库相关
  async getPhotos(options: any): Promise<any[]> {
    return this.ipcRenderer.invoke('db:get-photos', options)
  }

  async importPhotos(photos: any[]): Promise<{ success: boolean; count: number }> {
    return this.ipcRenderer.invoke('db:import-photos', photos)
  }

  // 缩略图相关
  async generateThumbnail(photoPath: string, size: number): Promise<string | null> {
    return this.ipcRenderer.invoke('thumbnail:generate', photoPath, size)
  }

  // 元数据相关
  async extractMetadata(photoPath: string): Promise<any> {
    return this.ipcRenderer.invoke('metadata:extract', photoPath)
  }

  // 事件监听
  on(channel: string, callback: Function): void {
    if (!this.listeners.has(channel)) {
      this.listeners.set(channel, [])
    }
    
    const listeners = this.listeners.get(channel)!
    listeners.push(callback)
    
    // 包装回调函数以确保类型安全
    const wrappedCallback = (event: any, ...args: any[]) => {
      callback(...args)
    }
    
    this.ipcRenderer.on(channel, wrappedCallback)
  }

  off(channel: string, callback: Function): void {
    const listeners = this.listeners.get(channel)
    if (listeners) {
      const index = listeners.indexOf(callback)
      if (index > -1) {
        listeners.splice(index, 1)
        // 移除 IPC 监听器
        this.ipcRenderer.removeAllListeners(channel)
        
        // 重新添加剩余的监听器
        listeners.forEach(listener => {
          const wrappedCallback = (event: any, ...args: any[]) => {
            listener(...args)
          }
          this.ipcRenderer.on(channel, wrappedCallback)
        })
      }
    }
  }

  send(channel: string, ...args: any[]): void {
    this.ipcRenderer.send(channel, ...args)
  }
}